package com.mmc.sqlSession;

import com.mmc.bean.User;
import com.mmc.container.Configration;
import com.mmc.container.MappedStatement;
import com.mmc.executor.Executor;
import com.mmc.executor.SimpleExecutor;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.List;

public class DefaultSqlSession implements SqlSession {

    private Configration configration;


    private Executor executor=new SimpleExecutor();

    public DefaultSqlSession(Configration configration) {
        this.configration = configration;
    }

    @Override
    public <T> List<T> queryAll(String statementid) throws IllegalAccessException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        MappedStatement mappedStatement = configration.getStatementMap().get(statementid);
        return executor.queryList(configration,mappedStatement,null);
    }

    @Override
    public <T> T queryOne(String statementid, Object... params) throws IllegalAccessException, IntrospectionException, InstantiationException, SQLException, InvocationTargetException, NoSuchFieldException {
        MappedStatement mappedStatement = configration.getStatementMap().get(statementid);
        List<T> objects = executor.queryList(configration, mappedStatement, params);
        if(objects!=null && objects.size()>0){
            return objects.get(0);
        }
        return null;
    }

    @Override
    public <T> T getMapper(Class mapperClass) {
        Object instance = Proxy.newProxyInstance(mapperClass.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("queryAll")) {
                    String className = method.getDeclaringClass().getName();
                    String statementid = className + "." + method.getName();
                    List<User> objects = queryAll(statementid);
                    return objects;
                }
                return null;
            }
        });
        return (T) instance;
    }
}
